package com.the_ring.chapter12.widget;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.Nullable;

import java.util.Calendar;

/**
 * 遮罩
 */
public class LayerView extends View {

    private Paint mUpPaint = new Paint();   // 上层画笔对象
    private Paint mDownPaint = new Paint(); // 下层画笔对象
    private Paint mMaskPaint = new Paint(); // 遮罩画笔对象
    private boolean onlyLine = true;        // 是否只绘制轮廓
    private PorterDuff.Mode mMode;          // 绘图模式

    public LayerView(Context context) {
        this(context, null);
    }

    public LayerView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        mUpPaint.setStrokeWidth(5);
        mUpPaint.setColor(Color.CYAN);
        mDownPaint.setStrokeWidth(5);
        mDownPaint.setColor(Color.RED);
    }

    // 设置绘图模式
    public void setMode(PorterDuff.Mode mode) {
        mMode = mode;
        onlyLine = false;
        mUpPaint.setStyle(Paint.Style.FILL);
        mDownPaint.setStyle(Paint.Style.FILL);
        postInvalidate();
    }

    public void setOnlyLine() {
        onlyLine = true;
        mUpPaint.setStyle(Paint.Style.STROKE);
        mDownPaint.setStyle(Paint.Style.STROKE);
        postInvalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        int width = getMeasuredWidth();
        int height = getMeasuredHeight();
        if (onlyLine) {
            canvas.drawRect(width / 3, height / 3, width * 9 /10, height * 9 / 10, mUpPaint);
            canvas.drawCircle(width / 3, height / 3, height / 3, mDownPaint);
        } else if (mMode != null) {
            // 创建一个遮罩位图
            Bitmap mask = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            Canvas canvasMask = new Canvas(mask);   // 创建一个遮罩画布
            // 先绘制上层矩阵
            canvasMask.drawRect(width / 3, height / 3, width * 9 / 10, height * 9 / 10, mUpPaint);
            // 设置离屏缓存
            int saveLayer = canvas.saveLayer(0, 0, width, height, null, Canvas.ALL_SAVE_FLAG);
            // 在绘制下层的图形
            canvas.drawCircle(width / 3, height / 3, height / 3, mDownPaint);
            // 设置混合模式
            mMaskPaint.setXfermode(new PorterDuffXfermode(mMode));
            canvasMask.drawBitmap(mask, 0, 0, mMaskPaint);  // 绘制源图图像的遮罩
            mMaskPaint.setXfermode(null);                           // 还原混合模式
            canvas.restoreToCount(saveLayer);                       // 还原画布
        }
    }
}
